<template>
  <div class="order-view">
    <el-dialog
      :title=title
      :visible.sync="addShow"
      width="60%"
      v-if="addShow"
      :before-close="handleClose"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <div>
        <el-form ref="form" :model="form" label-width="150px" label-position="left">
          <el-form-item label="销售退货单编号" prop="saleBackCode">
            <el-input v-model="form.saleBackCode" disabled placeholder="请输入销售退货单编号"/>
          </el-form-item>
          <el-form-item label="销售退货申请单编号" prop="saleBackRequestCode">
            <el-input v-model="form.saleBackRequestCode" placeholder="请选择销售退货申请单编号"
                      @focus="selSaleBackRequest"/>
          </el-form-item>
          <el-form-item label="客户名称" prop="cusName">
            <el-input disabled v-model="form.cusName" placeholder="请输入客户名称"/>
          </el-form-item>
          <el-form-item label="总价" prop="total">
            <el-input disabled v-model="form.total" placeholder="请输入总价"/>
          </el-form-item>
          <el-form-item label="总数量" prop="totalNum">
            <el-input disabled v-model="form.totalNum" placeholder="请输入总数量"/>
          </el-form-item>
        </el-form>
      </div>
      <!--        detail表格-->
      <el-table :data="saleBackDetailList" style="width: 100%">
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="proName"/>
        <el-table-column label="数量" align="center" prop="proNum">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.proNum"
              @change="handleInputChange(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <el-table-column label="小计" align="center">
          <template slot-scope="scope">
            {{ (scope.row.proNum * scope.row.price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row.proCode)"
              v-hasPermi="['xiaoshou:saleBackRequest:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="选择 销售退货申请单"
                 :visible.sync="showSelSaleBackRequest"
                 width="60%"
                 :before-close="handleClose"
                 :modal-append-to-body="false"
                 :append-to-body="true">
        <el-table :data="saleBackRequestList">
          <el-table-column label="序号" align="center">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="销售退货申请单编号" align="center" prop="saleBackRequestCode">
            <template slot-scope="scope">
              <el-button type="text" @click="confirmSaleBackRequest(scope.row)">{{
                  scope.row.saleBackRequestCode
                }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="销售出库单编号" align="center" prop="saleOutCode"/>
          <el-table-column label="总价" align="center" prop="total"/>
          <el-table-column label="创建时间" align="center" prop="createDate"/>
        </el-table>
        <pagination
          v-show="totalSize>0"
          :total="totalSize"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getSaleBackRequestList"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitForm">提 交</el-button>
        <el-button @click="closeAdd">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import request from '@/utils/request';
import {v4 as uuidv4} from 'uuid';

export default {
  name: "AddSaleBack",
  props: ["updData"],
  data() {
    return {
      title: "添加 销售退货申请",
      dialogVisible: false,
      addShow: false,
      isUpd: false,
      showSelSaleBackRequest: false,
      saleBackRequest: {},
      saleBackRequestList: [],
      saleBack: {},
      saleBackDetailList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      form: {
        saleBackCode: "",
        saleBackRequestCode: "",
        total: 0,
        payCent: 0,
        realMoney: 0,
        payMoney: 0,
      },
      totalDetail: 0,
      totalSize: 0,
      totalPrice: 0,
    };
  },
  watch: {
    totalPrice() {
      this.form.total = this.totalPrice;
    },
    updData() {
      this.form = this.updData;
      this.getSaleBackDetailList();
    }
  },
  methods: {
    handleDelete(proCode) {
      // 找到要删除的对象的索引
      const index = this.saleBackDetailList.findIndex(item => item.proCode === proCode);
      if (index !== -1) {
        // 使用 splice 删除对象
        this.saleBackDetailList.splice(index, 1);
        this.$notify({
          title: '成功',
          message: '已成功删除商品',
          type: 'success',
        });
      } else {
        this.$notify({
          title: '错误',
          message: '未找到要删除的商品',
          type: 'error',
        });
      }
      this.changeTotal();
    },
    reset() {
      this.resetForm("form");
      this.saleBack = {};
      this.saleBackRequestList = [];
    },
    //改变总价
    changeTotal() {
      let totalPri = 0;
      let totalNum = 0;
      if (this.saleBackDetailList != null) {
        this.saleBackDetailList.forEach(item => {
          // 计算每个商品的价格
          item.itemPrice = (parseFloat(item.price) * parseInt(item.proNum)).toFixed(2); // 确保 price 和 num 是数字
          // 累计总价格
          totalPri = totalPri + parseFloat(item.itemPrice);// 使用 parseFloat 将 itemPrice 转换为数字进行累加
          totalNum = parseInt(totalNum) + parseInt(item.proNum);
        });
      } else {
        totalPri = 0;
        totalNum = 0;
      }
      this.form.totalNum = totalNum;
      this.totalPrice = (totalPri).toFixed(2);
    },
    //修改输入框数量
    handleInputChange(row) {
      if (isNaN(row.proNum) || row.proNum <= 0) {
        this.$notify({
          title: '警告',
          message: '请输入正整数',
          type: 'warning',
        });
        row.proNum = row.inputNum; // 恢复为num
      }
      if (row.inputNum < row.proNum) {
        this.$notify({
          title: '警告',
          message: `输入的数量不能大于` + row.inputNum,
          type: 'warning',
        });
        row.proNum = row.inputNum; // 恢复为num
      }
      this.changeTotal();
    },
    showAdd() {
      this.form = {
        saleBackCode: "",
        saleBackRequestCode: "",
        total: 0,
        payCent: 0,
        realMoney: 0,
        payMoney: 0,
      };
      this.saleBackDetailList = [];
      this.title = "添加 销售退货订单";
      this.form.saleBackCode = "";
      this.form.saleBackCode = "XSTHDD" + new Date().getTime();
      this.addShow = true;
    },
    showUpd() {
      this.title = "修改 销售退货订单";
      this.isUpd = true;
    },
    getSaleBackDetailList() {
      this.saleBackDetailList = [];
      request({
        url: "/xiaoshou/saleBackDetail/list",
        params: {
          saleBackCode: this.form.saleBackCode
        },
        method: "get"
      }).then(res => {
        this.saleBackDetailList = res.rows;
        this.saleBackDetailList.forEach(item => {
          item.inputNum = item.proNum;
        })
        this.addShow = true;
      });
    },
    closeAdd() {
      this.reset();
      this.isUpd = false;
      this.addShow = false;
    },
    confirmSaleBackRequest(row) {
      this.saleBackRequest = row;
      this.form.saleBackRequestCode = row.saleBackRequestCode;
      this.form.cusName = row.cusName;
      //获取申请详情列表给到订单详情
      request({
        url: "/xiaoshou/saleBackRequestDetail/useList",
        params: {
          saleBackRequestCode: this.form.saleBackRequestCode
        },
        method: "get"
      }).then(res => {
        this.saleBackRequestDetailList = res.rows;
        this.saleBackDetailList = [];
        this.saleBackRequestDetailList.forEach(item => {
          const detail = {
            saleBackCoe: this.form.saleBackCode,
            proNum: item.proNum,
            proName: item.proName,
            inputNum: item.proNum,
            proCode: item.proCode,
            price: item.price,
            createBy: this.$store.getters.name
          }
          this.saleBackDetailList.push(detail);
        });
        this.changeTotal();
      });
      this.showSelSaleBackRequest = false;
    },
    handleClose(done) {
      done();
    },
    //获取已审核申请单列表
    getSaleBackRequestList() {
      this.queryParams.status = 1;
      request({
        url: "/xiaoshou/saleBackRequest/list",
        methods: "get",
        params: this.queryParams
      }).then(response => {
        this.saleBackRequestList = response.rows;
        this.totalSize = response.total;
      });
    },
    //弹出退货申请列表
    selSaleBackRequest() {
      this.getSaleBackRequestList();
      this.showSelSaleBackRequest = true;
    },
    check() {
      if (this.form.saleBackCode == null || this.form.saleBackCode == '') {
        this.$notify({
          title: "警告",
          message: "销售退货编号不能为空！",
          type: "warning",
        })
        return false;
      }
      if (this.form.saleBackRequestCode == null || this.form.saleBackRequestCode == '') {
        this.$notify({
          title: "警告",
          message: "退货申请编号不能为空！",
          type: "warning",
        })
        return false;
      }
      if (!this.form.total > 0) {
        this.$notify({
          title: "警告",
          message: "总价必须大于0！",
          type: "warning",
        })
        return false;
      }
      return true;
    },
    submitForm() {
      if (!this.check()) {
        return;
      }
      this.form.createBy = this.$store.getters.name;
      this.form.updateBy = this.$store.getters.name;
      this.saleBackDetailList.forEach(item => {
        item.saleBackCode = this.form.saleBackCode
        item.createBy = this.$store.getters.name
      })
      let saleBackDto = {
        saleBack: this.form,
        saleBackDetailList: this.saleBackDetailList
      };
      if (!this.isUpd) {
        request({
          url: "/xiaoshou/saleBack/addSaleBack",
          data: saleBackDto,
          method: "post",
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("新增成功");
            this.$emit("updList");
            this.addShow = false;
            this.reset();
          } else {
            this.$modal.msgError(res.msg);
          }
        }).catch(e => {
          this.$modal.msgError(e);
        })
      } else {
        request({
          url: "/xiaoshou/saleBack/updSaleBack",
          data: saleBackDto,
          method: "post",
        }).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess("修改成功");
            this.$emit("updList");
            this.addShow = false;
            this.reset();
          } else {
            this.$modal.msgError(res.msg);
          }
        }).catch(e => {
          this.$modal.msgError(e);
        })
      }

    },
    cancel() {
      this.showSelSaleBackRequest = false;
    }
  },
};
</script>
